<template>
  <div class="app-container" v-loading="loading">
    <el-card>
      <div id="addgoods">
        <div
          class="infinite-list"
          v-infinite-scroll="load"
          style="overflow: auto"
        >
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            style="height: 700px"
          >
            <el-tab-pane label="基础信息" name="基础信息">
              <el-form
                ref="form"
                :rules="rules"
                :model="form"
                label-width="120px"
                style="margin-top: 15px"
              >
                <el-form-item label="商品类型：" prop="type">
                  <el-radio-group v-model="radio1" @change="shitType">
                    <el-radio v-model="radio1" label="1" border
                      >普通商品</el-radio
                    >
                    <el-radio v-model="radio1" label="2" border
                      >卡密商品</el-radio
                    >
                    <el-radio v-model="radio1" label="3" border
                      >虚拟商品</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="供应商id：" prop="supplier_id">
                  <el-select
                    :disabled="GYSSFKX"
                    @change="changes"
                    v-model="form.supplier_id"
                    placeholder="请选择"
                    style="width: 510px"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.supplier_name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="商品名称：" prop="goods_name">
                  <el-input
                    v-model="form.goods_name"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入商品名称"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="副标题：" prop="sub_title">
                  <el-input
                    v-model="form.sub_title"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入商品副标题"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="类目ID：" prop="category_id">
                  <el-cascader
                    v-model="svalue"
                    :options="typeData"
                    :props="{
                      expandTrigger: 'hover',
                      checkStrictly: true,
                      value: 'id',
                      label: 'category_name',
                    }"
                    @change="handleChange"
                    placeholder="请选择类目"
                    style="width: 510px"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="商品主图：" prop="main_image">
                  <logo-upload
                    :single-file="main_images"
                    :show-file-list="false"
                    accept="image/jpeg, image/png"
                    @uploadCallback="logoCallback"
                  />
                </el-form-item>

                <el-form-item label="商品缩略图：" prop="thumbnail">
                  <logo-upload
                    :single-file="thumbnails"
                    :show-file-list="false"
                    accept="image/jpeg, image/png"
                    @uploadCallback="logoCallbacks"
                  />
                </el-form-item>
                <el-form-item label="商品轮播图：" prop="slider_image">
                  <logo-upload
                    :file-list="slider_images"
                    :show-file-list="true"
                    accept="image/jpeg, image/png"
                    @uploadCallback="logoCallbackss"
                  />
                </el-form-item>
                <el-form-item label="商品上下架状态：" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio label="1">上架</el-radio>
                    <el-radio label="0">下架</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="排序：" prop="sort">
                  <el-input
                    v-model="form.sort"
                    onkeyup="value=value.replace(/\D/g,'')"
                    maxlength="10"
                    show-word-limit
                    style="width: 510px"
                    placeholder="请输入排序"
                  ></el-input>
                </el-form-item>
                <el-form-item label="编码：" prop="product_code">
                  <el-input
                    v-model="form.product_code"
                    onkeyup="value=value.replace(/[^0-9a-zA-Z]/g,'')"
                    style="width: 510px"
                    maxlength="20"
                    show-word-limit
                    placeholder="选填"
                  ></el-input>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请输入..."
                    style="width: 510px"
                    maxlength="200"
                    show-word-limit
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <!-- <el-button type="primary" @click="submitForm('form')">保存</el-button> -->
                  <!-- <el-button>取消</el-button> -->
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="规格库存" name="规格库存">
              <!-- <el-form label-width="120px" >
                <el-form-item label="商品规格：">
                  <el-radio-group v-model="namesku" @change="shitTypes">
                    <el-radio v-model="namesku" label="单">单规格</el-radio>
                    <el-radio v-model="namesku" label="双">多规格</el-radio>
                  </el-radio-group>
                </el-form-item>
                </el-form> -->
              <el-form
                ref="forms"
                :rules="ruless"
                :model="forms"
                label-width="120px"
                style="margin-top: 15px"
                v-if="namesku == '单'"
              >
                <el-form-item label="规格名称：" prop="sku_name">
                  <el-input
                    v-model="forms.sku_name"
                    maxlength="20"
                    show-word-limit
                    placeholder="请输入规格名称"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="零售价：" prop="retail_price">
                  <el-input
                    v-model="forms.retail_price"
                    placeholder="请输入商品零售价"
                    type="number"
                    min="0"
                    max="1000000"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="成本价：" prop="cost_price">
                  <el-input
                    v-model="forms.cost_price"
                    type="number"
                    min="0"
                    max="1000000"
                    placeholder="请输入商品成本价"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="库存：" prop="inventory">
                  <el-input
                    v-model="forms.inventory"
                    type="number"
                    maxlength="10"
                    show-word-limit
                    placeholder="请输入商品库存"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="产品码：" prop="code">
                  <el-input
                    v-model="forms.code"
                    type="text"
                    onkeyup="value=value.replace(/[^0-9a-zA-Z]/g,'')"
                    placeholder="请输入商品产品码"
                    maxlength="20"
                    show-word-limit
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="库存预警：" prop="inventory_alert">
                  <el-input
                    v-model="forms.inventory_alert"
                    type="number"
                    maxlength="10"
                    min="0"
                    max="1000000"
                    show-word-limit
                    placeholder="请输入库存预警"
                    style="width: 510px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="单位：" prop="unit">
                  <el-input
                    v-model="forms.unit"
                    type="text"
                    maxlength="10"
                    show-word-limit
                    placeholder="请输入商品单位"
                    style="width: 510px"
                  ></el-input>
                  <!-- <el-select
                    @change="changesku"
                    v-model="form.unit"
                    placeholder="请选择"
                    style="width: 510px"
                  >
                    <el-option
                      v-for="item in skulist"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select> -->
                </el-form-item>
                <el-form-item label="图片：" prop="sku_img">
                  <logo-upload
                    :single-file="forms.sku_imgs"
                    :show-file-list="false"
                    accept="image/jpeg, image/png"
                    @uploadCallback="skuCallback"
                  />
                </el-form-item>
              </el-form>
              <el-form
                ref="forms"
                :rules="ruless"
                :model="forms"
                label-width="120px"
                v-else
              >
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="商品详情">
              <div style="margin-top: 15px">
                <tinymce-editor v-model="form.detail" :height="500" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="物流设置" name="物流设置">
              <el-form label-width="100px">
                <el-form-item
                  label="运费设置："
                  prop="delivery"
                  style="margin-top: 15px"
                >
                  <el-radio-group v-model="radio" @change="freghit">
                    <el-radio v-model="radio" label="1">固定运费</el-radio>
                    <el-radio v-model="radio" label="2">运费模版</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="运费设置：" v-if="radio == 1">
                  <el-input
                    type="number"
                    v-model="shipping_fee"
                    placeholder="请输入运费"
                    style="width: 300px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="运费模版：" v-if="radio == 2">
                  <el-select
                    @change="changefreight"
                    v-model="freight_template_id"
                    placeholder="请选择运费模版"
                    style="width: 510px"
                  >
                    <el-option
                      v-for="item in freight_template"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <!--  -->
        </div>
      </div>
    </el-card>
    <el-card>
      <div style="text-align: center">
        <el-button
          type="primary"
          v-if="activeName != '基础信息'"
          @click="backstep"
          >上一步</el-button
        >
        <el-button
          type="primary"
          v-if="activeName == '物流设置'"
          @click="submitsave('form')"
          >保存</el-button
        >
        <el-button
          type="primary"
          v-if="activeName == '基础信息'"
          @click="submitForm('form')"
          >下一步</el-button
        >
        <el-button
          type="primary"
          v-if="activeName == '规格库存'"
          @click="nextinventory('forms')"
          >下一步</el-button
        >
        <el-button
          type="primary"
          v-if="activeName == '商品详情'"
          @click="nextstep"
          >下一步</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import LogoUpload from "@/components/FileUpload";
import TinymceEditor from "@/components/Tinymce";
import {
  GoodsCateList,
  supplierLists,
  addsuppliergoods,
  getLabelList,
  freightgetList,
} from "@/api/supplier/index";
import { profile } from "@/api/admin/admin";
export default {
  name: "add",
  components: { LogoUpload, TinymceEditor },
  data() {
    return {
      radio: "1",
      checkboxGroup1: [],
      checkboxGroup2: [],
      activeName: "基础信息",
      svalue: "",
      freight_template: [],
      options: [],
      values: "点击关闭",
      value: "",
      radio1: "1",
      namesku: "单",
      forms: {
        sku_name: "", //规格名称
        retail_price: "", //零售价
        cost_price: "", //成本价
        inventory: "", //库存
        code: "", //产品码
        inventory_alert: 0, //库存预警
        unit: "", //单位
        sku_img: "", //规格图片
      },
      freight_template_id: "",
      shipping_fee: "", //运费
      sku_imgs: {}, //规格图片
      form: {
        id: "",
        supplier_id: "", //供应商ID
        sub_title: "", //副标题
        type: 1, //商品类型
        goods_name: "", //商品名字
        category_id: "", //类目ID
        thumbnail: "",
        goodsProductArray: [],
        main_image: "",
        slider_image: "",
        shipping_type: "",
        delivery_type: "", //配送方式

        status: "1", //状态
        sort: 100, //排序
        remark: "", //备注
        product_code: "", //编码
        detail: "", //商品详情
      },
      main_images: {},
      slider_images: [],
      thumbnails: {},
      rules: {
        supplier_id: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        sub_title: [
          { required: true, message: "请选择副标题", trigger: "change" },
        ],
        category_id: [
          { required: true, message: "请选择类目ID", trigger: "change" },
        ],
        main_image: [
          { required: true, message: "请上传主图", trigger: "change" },
        ],
        thumbnail: [
          { required: true, message: "请上传缩略图", trigger: "change" },
        ],
        slider_image: [
          { required: true, message: "请上传轮播图", trigger: "change" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "change" }],
      }, //表单验证
      ruless: {
        sku_name: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
        ],
        retail_price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入零售价"));
              } else {
                if (Number(value) > 1000000) {
                  return callback(new Error("不能大于1000000"));
                }
                let req = /^\d+(\.\d{1,2})?$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多只能保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        cost_price: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入成本价"));
              } else {
                if (Number(value) > 1000000) {
                  return callback(new Error("不能大于1000000"));
                }
                let req = /^\d+(\.\d{1,2})?$/;
                if (req.test(value)) {
                  callback();
                } else {
                  callback(new Error("最多只能保留两位小数"));
                }
              }
            },
            trigger: "change",
          },
        ],
        inventory: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (String(value).indexOf(".") !== -1) {
                return callback(new Error("请输入整数"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        // code: [{ required: , message: "请输入产品码", trigger: "blur" }],
        unit: [{ required: true, message: "请选择单位", trigger: "change" }],
        sku_img: [{ required: true, message: "请上传图片", trigger: "change" }],
      }, //表单验证
      tableData: [], //列表
      typeData: [], //类目list
      skulist: [], //单位list
      activename: "基础信息",
      // 供应商是否可选
      GYSSFKX: false,
      loading: true,
    };
  },
  mounted() {
    profile().then((res) => {
      if (res.data.supplier.id) {
        this.GYSSFKX = true;
        this.form.supplier_id = res.data.supplier.id;
      } else {
        this.GYSSFKX = false;
      }
      const p1 = new Promise((req, rej) => {
        GoodsCateList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            rej();
            return this.$messages.error(res.msg);
          }
          req();
          this.typeData = res.data;
        });
      });
      const p2 = new Promise((req, rej) => {
        supplierLists().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            rej();
            return this.$messages.error(res.msg);
          }
          req();
          this.options = res.data;
        });
      });
      const p3 = new Promise((req, rej) => {
        getLabelList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            rej();
            return this.$messages.error(res.msg);
          }
          req();
          this.skulist = res.data;
        });
      });
      const p4 = new Promise((req, rej) => {
        freightgetList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            rej();
            return this.$messages.error(res.msg);
          }
          req();
          this.freight_template = res.data.list;
        });
      });
      Promise.all([p1, p2, p3, p4])
        .then(() => {
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    });
  },
  methods: {
    freghit(i) {
      this.form.shipping_type = i;
    },
    //切换供应商ID
    changes(val) {
      this.form.supplier_id = val;
      console.log(this.form.supplier_id);
    },
    //切换运费模版ID
    changefreight(val) {
      this.freight_template_id = val;
      console.log(this.freight_template_id);
    },
    //切换规格单元
    changesku(val) {
      this.forms.unit = val;
    },
    //中间滚动
    load() {},
    //上一步
    backstep() {
      if (this.activename == "规格库存") {
        this.activeName = "基础信息";
        this.activename = "基础信息";
      }
      if (this.activename == "商品详情") {
        this.activeName = "规格库存";
        this.activename = "规格库存";
      }
      if (this.activename == "物流设置") {
        this.activeName = "商品详情";
        this.activename = "商品详情";
      }
    },
    //下一步
    nextstep() {
      if (this.activename == "商品详情") {
        this.activeName = "物流设置";
        this.activename = "物流设置";
        return;
      }
    },
    //切换商品类型
    shitType(i) {
      this.form.category_id = i;
    },
    //切换规格多还是单
    shitTypes(i) {},
    handleClick(tab, event) {
      this.activename = tab._props.name;
    },
    //保存
    submitsave(formName) {
      let array = [];
      array.push(this.forms);
      // return
      this.form.goodsProductArray = JSON.stringify(array);
      this.form.delivery_type = 1;
      if (this.form.shipping_type == 1) {
        this.form.shipping_fee = this.shipping_fee;
        this.form.freight_template_id = 0;
      } else {
        this.form.freight_template_id = this.freight_template_id;
        this.form.shipping_fee = 0;
      }
      if (!this.form.id) {
        this.form.id = "";
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addsuppliergoods(this.form).then((res) => {
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              return;
            }
            this.$messages.success("添加成功");
            setTimeout(() => {
              this.$router.back();
            }, 1500);
          });
        } else {
          this.$messages.warning("请完善信息");
          return false;
        }
      });
    },
    //规格tab点下一步
    nextinventory(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.activeName = "商品详情";
          this.activename = "商品详情";
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //确认提交表单
    submitForm(formName) {
      // console.log(this.form, "888888888888")
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.activeName = "规格库存";
          this.activename = "规格库存";
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 规格上传回调
    skuCallback(singleFile) {
      this.sku_imgs = singleFile;
      this.forms.sku_img = singleFile.url;
    },
    // 文件上传回调
    logoCallback(singleFile) {
      this.main_images = singleFile;
      this.form.main_image = singleFile.url;
    },
    // 文件上传回调
    logoCallbacks(singleFile) {
      this.thumbnails = singleFile;
      this.form.thumbnail = singleFile.url;
    },
    // 文件上传回调
    logoCallbackss(singleFile) {
      this.slider_images = singleFile;
      let obj = [];
      singleFile.forEach((item) => {
        obj.push(item.url);
      });
      let banners = obj.join();
      this.form.slider_image = banners;
    },
    //类目ID选中
    handleChange(value) {
      const length = value.length;
      const lastValue = value[length - 1];
      this.form.category_id = lastValue;
    },
    //供应商列表
    // SupplierLists() {
    //   supplierLists().then((res) => {
    //     this.options = res.data;
    //   });
    // },
    // //类目列表
    // getcartlist() {
    //   GoodsCateList().then((res) => {
    //     this.typeData = res.data;
    //   });
    // },
    //sku单位列表
    // SupplierskuLists() {
    //   getLabelList().then((res) => {
    //     this.skulist = res.data;
    //   });
    // },
  },
};
</script>

<style lang="scss">
.title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 16px;
}

.sn {
  color: #606266;
  font-size: 13px;
}

.order_center {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 50px 0 0;
  font-size: 13px;
  color: #666;
}

.fleximg {
  font-size: 12px;
  display: flex;
  align-items: center;
  color: #606266;
}

#addgoods .el-upload--picture-card {
  width: 90px !important;
  height: 90px !important;
  line-height: 90px;
}

#addgoods .el-upload-list--picture-card .el-upload-list__item-actions {
  width: 90px !important;
  height: 90px !important;
}

#addgoods .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 90px !important;
  height: 90px !important;
}

#addgoods .el-upload-list--picture-card .el-upload-list__item {
  width: 90px !important;
  height: 90px !important;
}
</style>
